import React, { Component } from 'react'
import { connect } from 'react-redux'

import { formatDuring, calcTime } from 'config/time'

import { switchChoiceHouseType } from 'model/house'

import style from './index.less'

@connect(state => ({
  building: state.building,
  house: state.house
}), {
  switchChoiceHouseType
})
export default class App extends Component {
  constructor (props) {
    super(props)

    this.timer = null

    this.state = {
      title: '',
      count: ''
    }

    this.updateTime = this.updateTime.bind(this)
  }

  componentDidMount () {
    this.updateTime()

    this.timer = setInterval(this.updateTime, 1000)
  }

  componentWillUnmount () {
    clearTimeout(this.timer)
    this.timer = null
  }

  updateTime (props) {
    const {
      switchChoiceHouseType,
      house: {
        type
      },
      building: {
        preSelectDate,
        preSelectEndDate,
        hobSpecificTime,
        hobSpecificEndTime,
      }
    } = props || this.props

    const {
      isPreSelect,
      isHobSpecific,

      startDiffPreSelect,
      endDiffPreSelect,
      startDiffHobSpecific,
      endDiffHobSpecific,

      mPreSelectEndDate,
      mHobSpecificTime,
      mHobSpecificEndTime
    } = calcTime(preSelectDate, preSelectEndDate, hobSpecificTime, hobSpecificEndTime)

    let title = ''
    let count = ''

    if (startDiffPreSelect > -1) {
      title = '距备选开始'
      count = formatDuring(startDiffPreSelect)
    } else if (endDiffPreSelect > -1 && !mPreSelectEndDate.isSame(mHobSpecificTime)) {
      title = '距备选结束'
      count = formatDuring(endDiffPreSelect)
    } else if (startDiffHobSpecific > -1) {
      title = '距选房开始'
      count = formatDuring(startDiffHobSpecific)
    } else if (endDiffHobSpecific > -1) {
      title = '距选房结束'
      count = formatDuring(endDiffHobSpecific)
    } else {
      // 没有设置选房结束时间
      title = '距选房结束'
      count = '** : ** : **'
    }

    this.setState({
      title,
      count
    })

    if (
      type !== 1 &&
      isHobSpecific &&
      !this.isHobSpecific
    ) {
      switchChoiceHouseType(1)
    }

    this.isPreSelect = isPreSelect
    this.isHobSpecific = isHobSpecific
  }

  render () {
    const {
      title,
      count
    } = this.state

    return (
      <div className = { style['alert'] }>
        <span className = { style['alert-title'] }>{ title }</span>
        <span className = { style['alert-value'] }>{ count }</span>
      </div>
    )
  }
}
